import { varRoutes, constRoutes, resetRouter } from "@/router";

const hasPermission = (permitIds, route) => {
  if (route.meta && route.meta.permitIds) {
    return permitIds.some(permitId => route.meta.permitIds.includes(permitId));
  } else {
    return true;
  }
};

const filterVarRoutes = (routes, permitIds) => {
  const res = [];
  routes.forEach(route => {
    const tmp = { ...route };
    if (hasPermission(permitIds, tmp)) {
      if (tmp.children) {
        // 如果有子路由就递归处理
        tmp.children = filterVarRoutes(tmp.children, permitIds);
      }
      res.push(tmp);
    }
  });

  return res;
};

const state = {
  routes: [],
  addRoutes: []
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constRoutes.concat(routes);
  },
  LOGOUT(state) {
    sessionStorage.clear();
    state.routes = [];
    resetRouter();
  }
};

const actions = {
  generateRoutes({ commit }, permitIds) {
    return new Promise(resolve => {
      let accessedRoutes;
      accessedRoutes = filterVarRoutes(varRoutes, permitIds);
      commit("SET_ROUTES", accessedRoutes);
      resolve(accessedRoutes);
    });
  },
  logout({ commit }) {
    commit("LOGOUT");
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
